package com.itheima.tliasmanagementspringboot.aspect;

import com.itheima.tliasmanagementspringboot.pojo.OperateLog;
import com.itheima.tliasmanagementspringboot.service.OperateLogService;
import com.itheima.tliasmanagementspringboot.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Slf4j
@Aspect
public class OperateAspect {
    @Autowired
    HttpServletRequest httpServletRequest;
    @Autowired
    OperateLogService operateLogService;

    @Around("@annotation(com.itheima.tliasmanagementspringboot.annotation.OperateLog)")
    public Object operateAround(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("增删改操作前置: ");
        OperateLog operateLog = new OperateLog();
         long start = System.currentTimeMillis();
        //操作人
        //思路,需要从令牌中获取
        String token = httpServletRequest.getHeader("token");
        //解析token
        Claims claims = JwtUtils.parseJWT(token);
        Integer id = (Integer)claims.get("id");
        operateLog.setOperateUser(id);

        //操作时间
        operateLog.setOperateTime(LocalDateTime.now());

        //执行方法的全类名
        operateLog.setClassName(pjp.getClass().getName());

        //执行方法名
        operateLog.setMethodName(pjp.getSignature().getName());

        //方法运行时参数
        operateLog.setMethodParams(Arrays.toString(pjp.getArgs()));

        Object result = pjp.proceed();

        operateLog.setReturnValue(result.toString());

        long end = System.currentTimeMillis();
        operateLog.setCostTime(end - start);
        operateLogService.insert(operateLog);

        return result;
    }
}
